package com.cari.oa.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.cari.oa.domain.AttachmentEntity;
import com.cari.oa.domain.CommentEntity;
import com.cari.oa.domain.OARepositoryEntity;
import com.cari.oa.service.AttachmentService;
import com.cari.oa.service.CommentService;
import com.cari.oa.service.OARepositoryService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.DateUtils;
import com.cari.oa.util.Utils;

@Controller
@SessionAttributes({"username", "usercnname"})
public class OARepositoryController extends BaseDownloadController{
	@Resource
	private OARepositoryService oARepositoryService;
	@Resource
	private CommentService commentService;
	@Resource
	private AttachmentService attachmentService;
	
	public static final String MODULE_NAME = "OA_REPOSITORY";
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
	}

	/**
	 * 分页查询知识内容
	 * @author -- liuyoujie
	 * @2013-6-18 下午5:50:29
	 * @param title			知识点标题
	 * @param creator		知识点创建者
	 * @param startTime		起始时间
	 * @param endTime		结束时间
	 * @param curPage		当前页
	 * @param totalPage		所有页
	 * @return
	 */
	@RequestMapping("req/oarepository/list.do")
	public String search(String title, String content, String creator, String starttime,
			String endtime, Integer curPage, ModelMap modelMap) {
		if(curPage == null)	curPage = 1;
		
		List<OARepositoryEntity> oARepositoryList = oARepositoryService.getPage(title, content, creator, 
				DateUtils.str2Timestamp(starttime, DateUtils.NORMAL_FORMAT), 
				DateUtils.str2Timestamp(endtime, DateUtils.NORMAL_FORMAT), 
				curPage, Contants.PAGE_SIZE);
		
		long totalRecords = oARepositoryService.getCount(title, content, creator, 
				DateUtils.str2Timestamp(starttime, DateUtils.NORMAL_FORMAT), 
				DateUtils.str2Timestamp(endtime, DateUtils.NORMAL_FORMAT));
		
		long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
		initContent(oARepositoryList);
		modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("totalPage", totalPage);
        modelMap.addAttribute("totalRecords", totalRecords);
        modelMap.addAttribute("oARepositoryList", oARepositoryList);
        
        modelMap.addAttribute("title", title);
        modelMap.addAttribute("creator", creator);
        modelMap.addAttribute("starttime", starttime);
        modelMap.addAttribute("endtime", endtime);
        modelMap.addAttribute("content", content);
        
		return "req/oarepository/list";
	}
	
	/**
	 * 插入知识点
	 * @author -- liuyoujie
	 * @2013-6-19 上午11:49:42
	 * @param entity
	 * @param username
	 * @return
	 */
	@RequestMapping(value="/req/oarepository/insert.do", method = RequestMethod.POST)
	@ResponseBody
	public String insert(@Valid OARepositoryEntity entity, @ModelAttribute("usercnname") String usercnname){
		entity.setCreator(usercnname);
		entity.setCreateTime(new Date());
		oARepositoryService.insert(entity);
		Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 1);
        resultMap.put("reqId", entity.getId());
        return JSON.toJSONString(resultMap);
	}
	
	/**
	 * 打开插入页面
	 * @author -- liuyoujie
	 * @2013-6-19 下午2:39:00
	 * @param qs		查询条件
	 * @param modelMap	
	 * @return
	 */
	@RequestMapping(value="/req/oarepository/insert.do", method=RequestMethod.GET)
	public String insert(String qs, ModelMap modelMap){
		modelMap.addAttribute("qs", qs);
		return "req/oarepository/insert";
	}
	
	@RequestMapping(value="/req/oarepository/update.do", method=RequestMethod.GET)
	public String update(String id, String qs, ModelMap modelMap){
		OARepositoryEntity entity = oARepositoryService.getById(id);
		if(entity == null)	return Utils.errorJsonResp("实体对象未找到");
		
		List<AttachmentEntity> attList = attachmentService.getByObjectId(id);
		List<CommentEntity> comList = commentService.getListByObjID(id,CommentService.CMT_OAREPOSITORY);
		modelMap.addAttribute("comList", comList);
		modelMap.addAttribute("attList", attList);
		
		modelMap.addAttribute("item", entity);
		modelMap.addAttribute("qs", qs);
		return "req/oarepository/update";
	}
	
	@RequestMapping(value="/req/oarepository/update.do", method=RequestMethod.POST)
	@ResponseBody
	public String update(OARepositoryEntity entity, @ModelAttribute("usercnname") String usercnname, 
			@ModelAttribute("username") String username,
			String qs, ModelMap modelMap){
		entity.setModifier(usercnname);
		entity.setModifyTime(new Date());
		oARepositoryService.update(entity);
		modelMap.addAttribute("qs", qs);
		
		//添加操作日志
		SysOperLogController.addOperLog(username, MODULE_NAME, "修改oa知识点" + entity.getContent());
		return Utils.normalJsonResp();
	}
	
	@RequestMapping(value="/req/oarepository/view.do", method=RequestMethod.GET)
	public String view(String id, ModelMap modelMap, String qs){
		OARepositoryEntity entity = oARepositoryService.getById(id);
		if(entity == null)	return Utils.errorJsonResp("实体对象未找到");
		
		List<AttachmentEntity> attList = attachmentService.getByObjectId(id);
		List<CommentEntity> comList = commentService.getListByObjID(id,CommentService.CMT_OAREPOSITORY);
		modelMap.addAttribute("comList", comList);
		modelMap.addAttribute("attList", attList);
		modelMap.addAttribute("item", entity);
		modelMap.addAttribute("qs", qs);
		return "req/oarepository/view";
	}
	@RequestMapping(value="/req/oarepository/comment.do", method=RequestMethod.POST)
	public void comment(@ModelAttribute("username") String username,
			@ModelAttribute("usercnname") String usercnname,
			String objectId, String comment, ModelMap modelMap,
			HttpServletResponse response) throws IOException{
		CommentEntity entity = new CommentEntity();
		entity.setObjectType(CommentService.CMT_OAREPOSITORY);
		entity.setContent(comment);
		entity.setCreateTime(new Date());
		entity.setObjectId(objectId);
		entity.setUserCnname(usercnname);
		entity.setUserEnname(username);
		
		commentService.insert(entity);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 1);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        resultMap.put("createTime",df.format(entity.getCreateTime()));
    	SysOperLogController.addOperLog(username, MODULE_NAME, "新增评论" + entity.getContent());
    	PrintWriter p =response.getWriter();
    	p.write(JSON.toJSONString(resultMap));
    	p.close();
	}
	
	@RequestMapping(value="req/oarepository/upload.do", method=RequestMethod.POST)
	public void upload(@ModelAttribute("usercnname") String username,HttpServletRequest request,HttpServletResponse response,BindingResult result){
		MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;
		multipartRequest.setAttribute("ObjectType",AttachmentService.OA_REPOSITORY_ATTACHEMENT_TYPE);
		multipartRequest.setAttribute("ObjectId",multipartRequest.getParameter("reqId"));
		System.out.println(multipartRequest.getParameter("reqId"));
		super.upload(username, multipartRequest);
	}
	
	@RequestMapping(value="req/oarepository/delete.do")
	@ResponseBody
	public String delete(OARepositoryEntity entity, HttpServletRequest request,@ModelAttribute("username") String username,
			String qs, ModelMap modelMap){
		oARepositoryService.delete(entity);
		
		//删除留言信息
		List<CommentEntity> commentList = commentService.getListByObjID(entity.getId(), CommentService.CMT_OAREPOSITORY);
		for(CommentEntity commentEntity : commentList)	commentService.delete(commentEntity);

		//删除附件信息
		List<AttachmentEntity> attachmentList = attachmentService.getByObjectId(entity.getId());
		for(AttachmentEntity attachEntity : attachmentList){
			String path = request.getSession().getServletContext().getRealPath("/") +  attachEntity.getPath();
			File file=new File(path);
			if(file.exists() && file.delete()){         //检查是否存在,删除文件
				attachmentService.deleteById(attachEntity.getId());
			}
		}
		modelMap.addAttribute("qs", qs);
		
		//添加操作日志
		SysOperLogController.addOperLog(username, MODULE_NAME, "删除oa知识点" + entity.getContent());
		return Utils.normalJsonResp();
	}
	/**
	 * 下载
	 */
	@RequestMapping("req/oarepository/download.do")
	public void download(String fileName,String path,HttpServletRequest request, HttpServletResponse response) {
		super.download(fileName, path, request, response);
	}
	
	/**
	 * 删除文件
	 */
	@RequestMapping("req/oarepository/deleteFile.do")
	@ResponseBody
    public String postDelete(@ModelAttribute("username") String username,HttpServletRequest request, String id,String path) {
		return super.postDelete(username, request, id, path);
    }
	
	/**
	 * 对长字段数据进行处理
	 * 使list页面上只显示前面50字符的内容
	 * @author -- liuyoujie
	 * @2013-6-20 上午11:33:32
	 * @param oARepositoryList
	 */
	private void initContent(List<OARepositoryEntity> oARepositoryList){
		for(OARepositoryEntity entity : oARepositoryList){
			if(entity.getContent() != null && entity.getContent().length() > 30)
				entity.setContent(entity.getContent().substring(0, 30) + ".....");
			if(entity.getProblem() != null && entity.getProblem().length() > 30)
				entity.setProblem(entity.getProblem().substring(0, 30) + "......");
			if(entity.getRemark() != null && entity.getRemark().length() > 30)
				entity.setRemark(entity.getRemark().substring(0, 30) + "......");
		}
	}
}
